import 'dart:async';

import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

class WebServiceLogic extends BaseController {
  // URL相关
  RxString url = ''.obs;

  // 加载状态
  RxDouble loadingProgress = 0.0.obs;
  RxBool isWebLoading = true.obs;
  RxBool hasError = false.obs;

  // RxString errorMessage = ''.obs;

  // WebView控制器
  InAppWebViewController? webViewController;

  // 防抖相关变量
  bool _isGoBackTapped = false;
  Timer? _goBackTimer;
  static const Duration _debounceDuration = Duration(milliseconds: 500);

  // List<String> consoleMessages = [];

  @override
  void onInit() {
    super.onInit();
    initializeUrl();
  }

  @override
  void onClose() {
    // 清理防抖定时器
    _goBackTimer?.cancel();
    _goBackTimer = null;
    _isGoBackTapped = false;

    webViewController = null;
    super.onClose();
    LoadingUtils.dismiss();
  }

  /// 初始化URL参数
  void initializeUrl() {
    final arguments = Get.arguments;
    if (arguments != null && arguments is Map<String, dynamic>) {
      final urlParam = arguments['url'] as String?;
      if (urlParam != null && urlParam.isNotEmpty) {
        url.value = urlParam;
      }
    } else {
      hasError.value = true;
    }
  }

  /// WebView加载开始
  void onLoadStart(InAppWebViewController controller, WebUri? url) {
    webViewController = controller;
    isWebLoading.value = true;
    hasError.value = false;
    loadingProgress.value = 0.0;
    clog('WebView开始加载: $url');
    // consoleMessages.add('WebView开始加载: $url');
    // LoadingUtils.showLoading(status: LocaleKeys.loading.tr);
  }

  /// WebView加载完成
  void onLoadStop(InAppWebViewController controller, WebUri? url) async {
    isWebLoading.value = false;
    loadingProgress.value = 1.0;
    LoadingUtils.dismiss();
    update();
  }

  /// WebView加载进度更新
  void onProgressChanged(InAppWebViewController controller, int progress) {
    loadingProgress.value = progress / 100.0;
    update();
  }

  /// WebView加载错误
  void onLoadError(InAppWebViewController controller, WebUri? url, int code,
      String message) {
    isWebLoading.value = false;
    hasError.value = true;
  }

  /// WebView HTTP错误
  void onLoadHttpError(InAppWebViewController controller, WebUri? url,
      int statusCode, String description) {
    isWebLoading.value = false;
    hasError.value = true;
  }

  /// 注册JavaScript处理器
  void registerJavaScriptHandlers() {
    if (webViewController == null) return;

    // 注册返回上一级页面的处理器
    webViewController!.addJavaScriptHandler(
      handlerName: 'goBack',
      callback: (args) {
        clog('JavaScript调用goBack方法，参数: $args');
        _handleGoBackWithDebounce();
        return {'status': 'ok'};
      },
    );

    clog('JavaScript处理器注册完成');
  }

  /// 防抖处理返回操作
  void _handleGoBackWithDebounce() {
    if (_isGoBackTapped) {
      clog('防抖：忽略重复的返回调用');
      if (!LoadingUtils.isShow) {
        LoadingUtils.showToast('操作过于频繁，请稍后再试');
      }
      return;
    }

    _isGoBackTapped = true;
    clog('执行返回操作（防抖处理）');

    // 执行返回操作
    Get.back();

    // 设置定时器重置防抖状态
    _goBackTimer?.cancel();
    _goBackTimer = Timer(_debounceDuration, () {
      _isGoBackTapped = false;
      clog('防抖状态已重置');
    });
  }
}
